<template>
  <div>
    <div>
      <TreeSelect style="width: 400px"
                  :options="core_orgList"
                  :normalizer="normalizer"
                  v-model="core_org.id"
                  :show-count="true"
                  placeholder="选择机构"
                  @select="handleOrgSelect"
      >
      </TreeSelect>
    </div>
    <div style="width: 70%;float: right;margin-top: -35px">
      <amap :zoom="zoom" :center="position" ref="grawAmap" style="z-index:99;width:100%;height:700px;">
        <div v-if="drawer.path">
          <amap-rectangle v-if="drawer.mode == 1" :bounds.sync="drawer.path" fill-color="#409EFF" stroke-color="#000A58" :fill-opacity="0.3" />
          <amap-circle v-if="drawer.mode == 2" :center.sync="drawer.path.center" :radius.sync="drawer.path.radius" fill-color="#409EFF" stroke-color="#000A58" :fill-opacity="0.5" />
          <amap-polygon v-if="drawer.mode == 3" :path.sync="drawer.path" fill-color="#409EFF" stroke-color="#000A58" :fill-opacity="0.5" />
        </div>
      </amap>

      <Button @click="drawerChange(2)">配置</Button>

    </div>
  </div>
</template>
<script>
import { info, queryByOrgId, updateAgency } from '@/api/amapvue/amapvue'
export default {
  components: {},
  data() {
    return {
      update:false,
      //半径
      radius:"0",
      core_orgList:[],
      lat:"",
      lon:"",
      Agency_scope:{
        id:"",
        agency_id:"",
        muti_points:"0"
      },
      core_org:{
        id:"",
        name:"",
        abbreviation:"",
        parent_id:"",
        org_type:"",
        province_id:"",
        city_id:"",
        county_id:"",
        address:"",
        contract_number:"",
        manager_id:"",
        tree_path:"",
        sort_value:"",
        status:"",
        describe:"",
        latitude:"",
        longitude:"",
        business_hours:"",
        create_user:"",
        update_time:"",
        update_user:"",
      },
      sounane:{
        id:"",
        name:""
      },
      from2:[{"id":"1","name":"张三"},{"id":"2","name":"张三"}],
      zoom: 4,//地图级别
      position: [116.378517,39.865246],//地图中心点
      drawer: {
        mode: 0,
        path: null,
      },
      mouseTool:null,
      objEditor:null,
      pathData:[]
    };
  },
  created(){
    info().then(res=>{
      this.core_orgList=res;
    })
  },
  methods: {
// 更新并重新加载数据的方法
    updateAndReloadData() {
      updateAgency(this.Agency_scope).then(res => {
        if (res.data === "修改成功") {
          // alert("机构范围修改成功");
          this.$message({
            type: 'success',
            message: '机构范围修改成功!'
          });
        } else if (res.data === "添加成功") {
          // alert("机构范围新增配置成功");
          this.$message({
            type: 'success',
            message: '机构范围新增配置成功!'
          });
        }

        queryByOrgId(this.Agency_scope.agency_id).then(res => {
          this.update = false;
          if (res) {
            this.Agency_scope = res;
          } else {
            this.Agency_scope = {
              id: "",
              agency_id: this.core_org.id,
              muti_points: "0"
            };
          }

          let mutiPoints2 = this.Agency_scope.muti_points;
          let startIndex = mutiPoints2.indexOf('],') + 2;
          let endIndex = mutiPoints2.length;
          let radius2 = mutiPoints2.substring(startIndex, endIndex);

          this.createCircleWithEditor(this.lon, this.lat, radius2, (newRadius) => {
            this.radius = newRadius;
          });
          // alert("后面" + this.radius);
        }).catch(error => {
          console.error("Error fetching data:", error);
        });
      });
    },




    updateFanWei(){
      let locationStr ="["+this.lon+","+this.lat+"]"+","+this.radius
      // this.Agency_scope.muti_points = this.radius;
      this.Agency_scope.muti_points = locationStr;
      const updateAndReloadData = () => {
        updateAgency(this.Agency_scope).then(res => {
          if (res.data === "修改成功") {
            // alert("机构范围修改成功");
            this.$message({
              type: 'success',
              message: '机构范围修改成功!'
            });
          } else if (res.data === "添加成功") {
            // alert("机构范围新增配置成功");
            this.$message({
              type: 'success',
              message: '机构范围新增配置成功!'
            });
          }

          queryByOrgId(this.Agency_scope.agency_id).then(res => {
            this.update = false;
            if (res) {
              this.Agency_scope = res;
            } else {
              this.Agency_scope = {
                id: "",
                agency_id: this.core_org.id,
                muti_points: "0"
              };
            }

            console.log("测试");
            console.log(this.Agency_scope);
            // alert(this.Agency_scope.muti_points);

            let mutiPoints2 = this.Agency_scope.muti_points;

// 通过截取字符串和正则表达式匹配来获取 radius 的值
            let startIndex = mutiPoints2.indexOf('],') + 2; // 找到第一个 '],' 的索引，并加上 2 得到 radius 的起始位置
            let endIndex = mutiPoints2.length; // 结束位置为字符串的末尾
            let radius2 = mutiPoints2.substring(startIndex, endIndex);
            // let radius = this.Agency_scope.muti_points;
            this.createCircleWithEditor(this.lon, this.lat, radius2, (newRadius) => {
              this.radius = newRadius; // 将新的半径值存储在 this.radius 中
            });

          }).catch(error => {
            console.error("Error fetching data:", error);
          });
        });
      };

      updateAndReloadData();
    },


    //用于根据传入的经纬度坐标和自定义图标创建标记并添加到地图
    addCustomMarkerToMap(longitude, latitude) {
      // 创建一个自定义图标
      var customIcon = new AMap.Icon({
        size: new AMap.Size(40, 44), // 图标尺寸
        image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png', // 自定义图标的地址
        imageSize: new AMap.Size(45, 49), // 图标大小
        imageOffset: new AMap.Pixel(-9, -3) // 图标偏移量
      });

      // 创建一个标记对象并设置自定义图标
      var marker = new AMap.Marker({
        position: [longitude, latitude],
        icon: customIcon,
        offset: new AMap.Pixel(-13, -30)
      });

      // 将标记添加到地图
      this.$refs.grawAmap.$map.add(marker);
    },


    handleOrgSelect(option) {
      console.log(option);
      let longitude = option.data.latitude;
      let latitude = option.data.longitude;
      this.position = [longitude,latitude];
      this.lat=latitude;
      this.lon=longitude;

      queryByOrgId(option.data.id).then(res => {
        if(res){
          this.Agency_scope = res;
        }else{
          this.Agency_scope={
            id:"",
            agency_id: this.core_org.id,
            muti_points:  "["+longitude+","+latitude+"]"+","+0
          }
        }
        let mutiPoints = this.Agency_scope.muti_points;

// 通过截取字符串和正则表达式匹配来获取 radius 的值
        let startIndex = mutiPoints.indexOf('],') + 2; // 找到第一个 '],' 的索引，并加上 2 得到 radius 的起始位置
        let endIndex = mutiPoints.length; // 结束位置为字符串的末尾
        let radius = mutiPoints.substring(startIndex, endIndex);
        // 在获取数据后执行创建圆形操作

        this.createCircleWithEditor(this.lon, this.lat, radius, (newRadius) => {
          this.radius = newRadius; // 将新的半径值存储在 this.radius 中
        });

      }).catch(error => {
        console.error("Error fetching data:", error);
      });

      // 设置地图缩放级别和添加自定义标记等其他操作可以继续保留
      this.zoom = 15;
      this.addCustomMarkerToMap(longitude, latitude);
    },

    /** 转换菜单数据结构 */
    normalizer(node) {
      console.log(node)
      if (node.data && node.data.id !== null && node.data.id !== undefined) {
        return {
          id: node.data.id,
          label: node.data.name,
          children: node.children
        };
      }
    },

    createCircleWithEditor(centerLongitude, centerLatitude, defaultRadius, adjustCallback) {
      let vm = this;
      let map = vm.$refs.grawAmap.$map;

      // 清除地图上已经存在的圆形对象
      if (this.existingCircle) {
        this.existingCircle.setMap(null);
        this.existingCircle = null;
      }

      // 清除原有的中心点和半径标记
      if (this.marker1) {
        this.marker1.setMap(null);
        this.marker1 = null;
      }
      if (this.marker2) {
        this.marker2.setMap(null);
        this.marker2 = null;
      }


      // 创建固定中心点的新圆形并添加到地图
      let circleCenter = [centerLongitude, centerLatitude];
      let newCircle = new AMap.Circle({
        center: circleCenter,
        radius: defaultRadius,
        strokeWeight: 1,
        strokeColor: "#0091ea",
        strokeOpacity: 1,
        fillOpacity: 0.3,
        fillColor: "#80d8ff",
        draggable: false
      });
      newCircle.setMap(map);

      // 异步加载CircleEditor插件
      AMap.plugin(['AMap.CircleEditor'], () => {
        if (this.update) {
          // 绘制新圆形后启用编辑功能
          setTimeout(() => {
            let objEditor = new AMap.CircleEditor(map, newCircle);
            objEditor.open();



            // 监听 adjust 事件以执行回调函数
            objEditor.on('adjust', (event) => {
              let newRadius = event.target.getRadius();
              console.log("调整后的半径：", newRadius);
              vm.radius = newRadius;
              // alert("调整后的半径:" + vm.radius + "纬度:" + vm.lon);

              // 计算地图缩放级别
              let bounds = event.target.getBounds();
              map.setBounds(bounds);

              // 在调整结束后，关闭编辑功能并移除半径点
              objEditor.close(); // 关闭编辑功能
              // objEditor.open(); // 重新打开编辑功能以移除半径点
              adjustCallback(newRadius);
              // 在调整结束后执行更新操作
              vm.updateFanWei();
            });
          }, 0);
        }else{
          newCircle.setDraggable(false);
        }
      });

      this.existingCircle = newCircle;
    },
    drawerChange(type) {
      this.update=true;
      let centerLongitude = this.lon;
      let centerLatitude = this.lat;

      this.drawer.path = null;
      this.drawer.mode = type;
      this.mouseTool ? this.mouseTool.close(true) : ''; // 取消鼠标工具

      switch (type) {
        case 1:
          this.mouseTool.rectangle(); // 鼠标工具 画矩形
          break;
        case 2:
          console.log("半径是多少")
          console.log(this.Agency_scope)
          let mutiPoints1 = this.Agency_scope.muti_points;

// 通过截取字符串和正则表达式匹配来获取 radius 的值
          let startIndex = mutiPoints1.indexOf('],') + 2; // 找到第一个 '],' 的索引，并加上 2 得到 radius 的起始位置
          let endIndex = mutiPoints1.length; // 结束位置为字符串的末尾
          let radius1 = mutiPoints1.substring(startIndex, endIndex);
          this.createCircleWithEditor(centerLongitude, centerLatitude, radius1, (newRadius) => {
            this.radius = newRadius; // 将新的半径值存储在 this.radius 中
          });


          break;
        case 3:
          this.mouseTool.polygon(); // 鼠标工具 画多边形
          break;
      }
    },
    eliminateChange(){
      this.mouseTool ? this.mouseTool.close(true) : '' //鼠标工具 取消
      this.objEditor ? this.objEditor.close() : '' //绘制 取消编辑 关闭编辑功能
      this.drawer.mode = 0
      this.drawer.path=null
    }




  }
};
</script>
<style scoped></style>
